<template>
  <div class="edit-product">
    <div class="page-header">
      <h1>编辑商品</h1>
      <el-button @click="$router.push('/products')">返回列表</el-button>
    </div>
    
    <el-card>
      <el-form
        ref="productFormRef"
        :model="productForm"
        :rules="productRules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="productForm.name" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="商品编号" prop="sku">
              <el-input v-model="productForm.sku" placeholder="请输入商品编号" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品分类" prop="category">
              <el-select v-model="productForm.category" placeholder="请选择分类" style="width: 100%">
                <el-option label="电子产品" value="electronics" />
                <el-option label="服装" value="clothing" />
                <el-option label="食品" value="food" />
                <el-option label="家居" value="home" />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="品牌" prop="brand">
              <el-input v-model="productForm.brand" placeholder="请输入品牌" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="价格" prop="price">
              <el-input-number
                v-model="productForm.price"
                :min="0"
                :precision="2"
                :step="0.01"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="库存" prop="stock">
              <el-input-number
                v-model="productForm.stock"
                :min="0"
                :step="1"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="重量(kg)" prop="weight">
              <el-input-number
                v-model="productForm.weight"
                :min="0"
                :precision="2"
                :step="0.1"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="商品图片" prop="images">
          <el-upload
            class="upload-demo"
            action="#"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-upload="beforeUpload"
            :file-list="productForm.images"
            list-type="picture"
            multiple
          >
            <el-button type="primary">
              <el-icon><Upload /></el-icon>
              上传图片
            </el-button>
            <template #tip>
              <div class="el-upload__tip">
                只能上传 jpg/png 文件，且不超过 2MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
        
        <el-form-item label="商品描述" prop="description">
          <el-input
            v-model="productForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入商品描述"
          />
        </el-form-item>
        
        <el-form-item label="商品详情" prop="detail">
          <div class="editor-container">
            <textarea
              v-model="productForm.detail"
              placeholder="请输入商品详情"
              class="editor"
            />
          </div>
        </el-form-item>
        
        <el-form-item label="商品状态" prop="status">
          <el-radio-group v-model="productForm.status">
            <el-radio label="active">上架</el-radio>
            <el-radio label="inactive">下架</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="loading">
            保存修改
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'

const router = useRouter()
const route = useRoute()
const productFormRef = ref()
const loading = ref(false)

const productForm = reactive({
  id: '',
  name: '',
  sku: '',
  category: '',
  brand: '',
  price: 0,
  stock: 0,
  weight: 0,
  images: [],
  description: '',
  detail: '',
  status: 'active'
})

const productRules = {
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  sku: [
    { required: true, message: '请输入商品编号', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择商品分类', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '价格必须大于等于0', trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入商品库存', trigger: 'blur' },
    { type: 'number', min: 0, message: '库存必须大于等于0', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入商品描述', trigger: 'blur' }
  ]
}

onMounted(() => {
  // 模拟加载商品数据
  const productId = route.params.id
  loadProductData(productId)
})

const loadProductData = (id) => {
  // 模拟从API获取数据
  productForm.id = id
  productForm.name = 'iPhone 15 Pro Max'
  productForm.sku = 'PHONE001'
  productForm.category = 'electronics'
  productForm.brand = 'Apple'
  productForm.price = 9999
  productForm.stock = 50
  productForm.weight = 0.221
  productForm.description = '苹果最新旗舰手机，搭载A17 Pro芯片，钛金属设计'
  productForm.detail = 'iPhone 15 Pro Max 是苹果公司的最新旗舰手机，采用钛金属材质，搭载A17 Pro芯片，支持USB-C接口，配备4800万像素主摄，支持5倍光学变焦。'
  productForm.status = 'active'
  productForm.images = [
    {
      name: 'product1.jpg',
      url: 'https://via.placeholder.com/200x200/409EFF/FFFFFF?text=Product1'
    }
  ]
}

const handlePreview = (file) => {
  console.log('Preview file:', file)
}

const handleRemove = (file, fileList) => {
  console.log('Remove file:', file, fileList)
}

const beforeUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('只能上传 JPG/PNG 格式的图片!')
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}

const handleSubmit = async () => {
  if (!productFormRef.value) return
  
  await productFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      
      try {
        // 模拟更新
        ElMessage.success('商品更新成功')
        router.push('/products')
      } catch (error) {
        ElMessage.error('更新失败，请重试')
      } finally {
        loading.value = false
      }
    }
  })
}

const handleReset = () => {
  if (productFormRef.value) {
    productFormRef.value.resetFields()
  }
}
</script>

<style scoped>
.edit-product {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  font-size: 24px;
  color: #333;
}

.editor-container {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
}

.editor {
  width: 100%;
  min-height: 200px;
  border: none;
  outline: none;
  resize: vertical;
  font-family: inherit;
  font-size: 14px;
}

.upload-demo {
  width: 100%;
}
</style>
